const HTTPSuccessFn = function (res) {
  return res.data
}

const HandleServerError = function (data) {
  if (data.code !== 200 && data.code !== 123) {
    return Promise.reject(data)
  }

  return typeof data.data === 'undefined' ? data : data.data
}


const HTTPFailedFn = function (err) {
  console.log('@err', err)
  if (err.code === 'ECONNREFUSED') {
    return Promise.reject(err)
  }

  if (err.message === 'Network Error') {
    return Promise.reject(err)
  }

  if (err.code) {
    return Promise.reject(err)
  }

  try {
    if (err.response && err.response.data && err.response.data.code) {
      err = err.response.data
    }
  } catch (_err) {
    err = _err
  }

  return Promise.reject(err)
}

/*
    params:
        - options
        {
            method,
            header, 微信是header，普通js的是headers
            url,
            params,
            data
        }
*/
const foo = function (options) {
  return wx.pro.request(options).then(HTTPSuccessFn)
    .then(HandleServerError)
    .catch(HTTPFailedFn)
}

export default foo
